﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;

namespace WebFormBlog
{
    public partial class Post : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);
            /*
            BlogDataSetTableAdapters.postTableAdapter pta = new BlogDataSetTableAdapters.postTableAdapter();
            BlogDataSet.postDataTable pdt = pta.GetDataById(id);
            if (pdt.Rows.Count == 0)
                throw new HttpException(404, "Post not found");
            PostRepeater.DataSource = pdt;
            PostRepeater.DataBind();
            */
            BlogModel.BlogEntities db = new BlogModel.BlogEntities();
            var post = from pst in db.posts
                       where pst.id == id
                       select new
                       {
                           id = pst.id,
                           title = pst.title,
                           created_at = pst.created_at,
                           content = pst.content,
                           catid = pst.catid,
                           cattitle = pst.category.title,
                           commentcount = pst.commentcount
                       };
            if (post == null)
                throw new HttpException(404, "Post not found");
            PostRepeater.DataSource = post;
            PostRepeater.DataBind();

            var the_post = post.FirstOrDefault();
            var prev_post = (from pst in db.posts
                            where pst.id < the_post.id
                            orderby pst.id descending
                            select new
                            {
                                id = pst.id,
                                title = pst.title
                            }).Take(1).FirstOrDefault();
            var next_post = (from pst in db.posts
                             where pst.id > the_post.id
                             orderby pst.id ascending
                             select new
                             {
                                 id = pst.id,
                                 title = pst.title
                             }).Take(1).FirstOrDefault();
            if (prev_post != null)
            {
                prev.Attributes["href"] = "Post.aspx?id=" + prev_post.id;
                prev.Title = prev_post.title;
            }
            else
            {
                prev.Visible = false;
            }

            if (next_post != null)
            {
                next.Attributes["href"] = "Post.aspx?id=" + next_post.id;
                next.Title = next_post.title;
            }
            else
            {
                next.Visible = false;
            }
        }
    }
}